<?php



namespace app\modules\admin\models;

use Yii;
use yii\web\IdentityInterface;
use yii\helpers\Url;
use yii\base\Exception;
use app\modules\admin\models\CallProcedure;
use app\modules\admin\models\AesManageForm;
use AlipaySubmit;
/**
 * ContactForm is the model behind the contact form.
 */

class PublicMethod
{
    public static function Getworkorderstep(){
        $array=array(
            '101'=>'到店登记',
            '102'=>'证件与物品确认',
            '103'=>'车辆核验',
            '104'=>'安装车载设备',
            '105'=>'车辆清洗',
            '106'=>'物品登记存放',
            '107'=>'汽车入场',
            '108'=>'工单完成',

            '201'=>'电话已确认',
            '202'=>'车辆清洗',
            '203 '=>'到店登记',
            '204 '=>'车辆核验',
            '205 '=>'支付订单押金',
            '206'=>'汽车离场',
            '207'=>'工单完成',


            '301 '=>'电话已确认',
            '302 '=>'到店登记',
            '303 '=>'车辆核验',
            '304 '=>'额外项目确认',
            '305 '=>'支付违章押金',
            '306 '=>'车辆清洗',
            '307 '=>'汽车入场',
            '308'=>'工单完成',

            '401'=>'电话已确认',
            '402'=>'车辆清洗',
            '403'=>'到店登记',
            '404'=>'车辆核验',
            '405'=>'拆除车载设备',
            '406'=>'额外项目确认',
            '407'=>'汽车离场',
            '408'=>'工单完成',
        );

        return $array;

    }

    //验证指纹
    public static function  finerprint_check($Procedure)
    {

        $ProcedureData = array(
            'Procedure_name' => 'Api_FingerPrintCheck',
            'Procedure_data_in' => array(
                'u_userid' =>$Procedure['u_userid'],
                'f_print' => $Procedure['f_print'],
            ),
            'Procedure_data_out' => array(
                'result_state' => 'result_state'
            )
        );

        $UserManage = new CallProcedure();    //Api_FingerPrintCheck

        try {

            $data = $UserManage->CallProcedure_query($ProcedureData);

        } catch (\Exception $ex) {
            $result['err_code'] = 40001;
            $result['err_msg'] = $ex->getMessage(); //  服务器错误
            return json_encode($result);
        }

        if (is_array($data) && !array_key_exists('result', $data) && !array_key_exists('value', $data)) {

            if ($data[0][0]['result_state'] == 1) {
                $result['result_state']=1;
            } else {
                switch ($data[0][0]['result_state']) {
                    case 0:
                        $result['err_code'] = 50010;
                        $result['err_msg'] = '指纹不存在';
                        break;
                    case -1:
                        $result['err_code'] = 50011;
                        $result['err_msg'] = '指纹已过期';
                        break;
                    default:
                        $result['err_code'] = 50010;
                        $result['err_msg'] = '指纹不存在'; //  服务器错误
                        break;
                }

            }
            return json_encode($result);
        }else {
            $result['err_code'] = 40002;
            $result['err_msg'] = $data['value'];
            return json_encode($result);
        }

    }

    //传入传出数据
    public  static function a_interface_history_insert($_type,$_call_content,$_response_content){

        $ProcedureData = array(
            'Procedure_name' => 'a_interface_history_insert',
            'Procedure_data_in' => array(
                '_type' =>$_type,
                '_call_content' => $_call_content,
                '_response_content' => $_response_content,

            )
        );

        $UserManage = new CallProcedure();    //Api_FingerPrintCheck

        $UserManage->CallProcedure_execute($ProcedureData);
    }

    //发送验证码 第三方接口
    public static  function  mobilecode_send($Procedure){

        $ProcedureData = array(
            'Procedure_name' => 'Api_FingerPrintCheck',
            'Procedure_data_in' => array(
                'u_userid' =>$Procedure['u_userid'],
                'f_print' => $Procedure['f_print'],
            ),
            'Procedure_data_out' => array(
                'result_state' => 'result_state'
            )
        );

        $UserManage = new CallProcedure();    //Api_FingerPrintCheck

        try {

            $data = $UserManage->CallProcedure_query($ProcedureData);

        } catch (\Exception $ex) {
            $result['err_code'] = 40001;
            $result['err_msg'] = $ex->getMessage(); //  服务器错误
            return json_encode($result);
        }

        if (is_array($data) && !array_key_exists('result', $data) && !array_key_exists('value', $data)) {

            if ($data[0][0]['result_state'] == 1) {
                $result['result_state']=1;
            } else {
                switch ($data[0][0]['result_state']) {
                    case 0:
                        $result['err_code'] = 50010;
                        $result['err_msg'] = '指纹不存在';
                        break;
                    case -1:
                        $result['err_code'] = 50011;
                        $result['err_msg'] = '指纹已过期';
                        break;
                    default:
                        $result['err_code'] = 50010;
                        $result['err_msg'] = '指纹不存在'; //  服务器错误
                        break;
                }

            }
            return json_encode($result);
        }else {
            $result['err_code'] = 40002;
            $result['err_msg'] = $data['value'];
            return json_encode($result);
        }

    }


    //后台验证  手机验证码
    public  static function  mobilecode_check($data){



        $ProcedureData = array(
            'Procedure_name' => 'Api_MobilecodeCheck',
            'Procedure_data_in' => array(
                'u_mobile' =>$data['u_mobile'],
                'm_mobilecode' => $data['m_mobilecode'],
            ),
            'Procedure_data_out' => array(
                'result_state' => 'result_state'
            )
        );

        $UserManage = new CallProcedure();    //Api_FingerPrintCheck

        try {

            $data = $UserManage->CallProcedure_query($ProcedureData);

        } catch (\Exception $ex) {
            $result['err_code'] = 40001;
            $result['err_msg'] = $ex->getMessage(); //  服务器错误
            return json_encode($result);
        }

        if (is_array($data) && !array_key_exists('result', $data) && !array_key_exists('value', $data)) {

            if ($data[0][0]['result_state'] == 1) {
                $result['result_state']=1;
            } else {
                switch ($data[0][0]['result_state']) {
                    case 0:
                        $result['err_code'] = 50040;
                        $result['err_msg'] = '验证码不存在';
                        break;
                    case -1:
                        $result['err_code'] = 50041;
                        $result['err_msg'] = '验证码已过期';
                        break;
                    default:
                        $result['err_code'] = 50041;
                        $result['err_msg'] = '验证码已过期'; //  服务器错误
                        break;
                }

            }
            return json_encode($result);
        }else {
            $result['err_code'] = 40002;
            $result['err_msg'] = $data['value'];
            return json_encode($result);
        }


    }


    //验证种子  和 解密数据
    public  static function  tokenseed_check($data){


        //判断是否有 种子
        session_start();


        if( array_key_exists("TokenSeed",$_SESSION)){   //存在种子


            if(array_key_exists("api_value", $data)){

                $session_id=session_id();
                $TokenSeed=$_SESSION['TokenSeed'];
                $TokenPassword=md5($session_id.$TokenSeed);

                $key=md5($TokenPassword);

                $iv='1415920000000065';  //1, 4, 1, 5, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 6, 5,  //1234567812345678

                var_dump($key);
                var_dump($data['api_value']);
                try{
                    $decode = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data['api_value'], MCRYPT_MODE_CBC, $iv);  //解密
                    var_dump($decode);
                    $decode=  json_decode(str_replace("\0", "", $decode),true);
                }catch (\Exception $ex) {
                    $result['err_code'] = 40005;
                    $result['err_msg'] = $ex->getMessage(); //  数据解密失败
                    return $result;
                }

            }else{
                $result['err_code'] = 40004;
                $result['err_msg'] = "参数不存在"; //
                return $result;
            }

        }else{  //不存在
            $result['err_code'] = 40003;
            $result['err_msg'] = "加密凭证不存在"; //    重新获取加密凭证  种子

            return $result;

        }



        if(is_array($decode)){
            $decode['key']=$key;
            $decode['iv']=$iv;
            return $decode;


        }else{
            $result['err_code'] = 40006;
            $result['err_msg'] = "数据格式不对,解密失败"; //    重新获取加密凭证  种子
            return $result;
        }

    }


    //图片存储 返回路径
    public  static  function  deal_image($type,$date){

        try{
            $rootPath = Yii::getAlias('@uploads').'/'; //上传根目录
            $randfileName1 = date('YmdHis',time()).rand(100000, 999999);//.".".$ext;//随机生成一个文件名


            $a = file_put_contents($rootPath.$type.'/'.$randfileName1.'.jpg', base64_decode(str_replace('data:image/jpg;base64,','',$date)));//返回的是字节数


        }catch (\Exception $ex) {
            $result['err_code'] = 40011;
            $result['err_msg'] ="图片资源错误"; //  服务器错误
            return json_encode($result);
        }

    }


    // APP端验证和解密数据
    public  static function  parameters_check(){

        $data=yii::$app->request->post();
        //判断是否有 种子
        session_start();
        date_default_timezone_set('UTC');
        $lifeTime =time() + 3600;

        if( array_key_exists("TokenSeed",$_SESSION)){   //存在种子


            if(array_key_exists("api_value", $data)){

                $session_id=session_id();
                //延长时间
                setcookie("PHPSESSID", $session_id,$lifeTime, "/");

                $TokenSeed=$_SESSION['TokenSeed'];
                setcookie("TokenSeed", $TokenSeed,$lifeTime, "/");

                $key=md5($session_id.$TokenSeed);


                try{

                    $AesManageForm=new AesManageForm($key);

                    $decode1=$AesManageForm->decrypt($data['api_value']);
                    $decode2=  json_decode($decode1,true);

                }catch (\Exception $ex) {
                    $result['err_code'] = 40005;
                    $result['err_msg'] = $ex->getMessage(); //  数据解密失败
                    return $result;
                }


            }else{
                $result['err_code'] = 40004;
                $result['err_msg'] = "参数不存在"; //
                return $result;
            }
        }else{  //不存在
            $result['err_code'] = 40003;
            $result['err_msg'] = "加密凭证不存在"; //    重新获取加密凭证  种子
            //   $result['err_msg2'] = session_id(); //    重新获取加密凭证  种子
            return $result;
        }



        if(is_array($decode2)){

            foreach ($decode2 as $ke =>$value){
                if(is_array($value)){
                    foreach ($value as  $k =>$val){
                        $decode[$ke][$k]=urldecode($val);
                    }
                }else{
                    $decode[$ke]=urldecode($value);
                }
            }

            $decode['key']=$key;
            return $decode;


        }else{
            $result['err_code'] = $data['api_value'];
            $result['err_msg'] =$decode1; //    重新获取加密凭证  种子
            return $result;
        }

    }

    //支付宝的物理类    支付租车订单
    public function alipaypayment($payment_id)
    {
        $subject="";
        $subject="name";$total_fee="0.01";$show_url="http://www.baidu.com";$body="";
        $postdate['_payment_id']=$payment_id;
        $ProcedureData=array(
            'Procedure_name'=>'alipay_getinfotopay',
            'Procedure_data_in'=>$postdate
        );
        $Procedure = new CallProcedure();
        try {
            $result = $Procedure->CallProcedure_query($ProcedureData);

        }catch (\Exception $ex)
        {
            return $ex->getMessage();
        }
        if(!array_key_exists("result",$result))
        {

            $alipay_config=yii::$app->params["alipay_config"];
            switch($result[0][0]["payment_time_type"])
            {
                case "1":$subject="租车预定支付";break;
                case "2":$subject="租车取车支付";break;
                case "3":$subject="租车还车支付";break;
                case "4":$subject="租车还车后支付";break;
                case "6":$subject="泊车预定支付";
                    $alipay_config['return_url']=$alipay_config['parking_url'];
                    break;
                default:$subject="其他支付";break;
            }

            //构造要请求的参数数组，无需改动
            $parameter = array(
                "service"       => $alipay_config['service'],
                "partner"       => $alipay_config['partner'],
                "seller_id"  => $alipay_config['seller_id'],
                "payment_type"	=> $alipay_config['payment_type'],
                "notify_url"	=> $alipay_config['notify_url'],
                "return_url"	=> $alipay_config['return_url'],
                "_input_charset"	=> trim(strtolower($alipay_config['input_charset'])),
                "out_trade_no"	=> date('YmdHis').$result[0][0]["payment_id"], //商户订单号
                "subject"	=> $subject,//订单名称
                "total_fee"	=> "0.01",//付款金额$result[0][0]["payment_cost"]
                "show_url"	=> "",//商品展示网址
                "body"	=> "",//商品描述
                //其他业务参数根据在线开发文档，添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.2Z6TSk&treeId=60&articleId=103693&docType=1
                //如"参数名"	=> "参数值"   注：上一个参数末尾需要“,”逗号。

            );
            $AlipaySubmit=new AlipaySubmit($alipay_config);
            //var_dump("1111");
            $html_text = $AlipaySubmit->buildRequestForm($parameter,"get", "确认");
            return $html_text;
        }
    }

    //预授权交易
    /*
     *参数说明：$cardNo-银行信用卡卡号
     *参数说明：$cardexpiredDate-卡有效期
     *参数说明：$cvv2-卡背后三位
     *参数说明：$cash-交易金额
     *参数说明：$username-持卡人姓名 '华磊'
     *参数说明：$cardHolderId-持卡人身份证号'420621197508210559'
     *参数说明：$phone-持卡人手机号
     *参数说明：$order_id-订单id
     *参数说明：$type-1代表订单押金，2代表违章押金
     *数据返回数组$returnarray
     * key:result  1代表彻底成功，2代表提交成功，等待返回结果，3代表网络错误，4代表重复的预授权，5代表数据库操作失败，6代表信用卡错误
     * key:msg 当result=0或1时返回块钱回调数组，否则返回错误信息字符串
     */
    public function sendprecredit($cardNo,$cardexpiredDate,$cvv2,$cash,$username,$cardHolderId,$phone,$order_id,$type)
    {



        $cash='1';
        $flag=0;
        //外部检索参考号  用于商户自定义标识一笔交易
        $externalRefNumber = date('YmdHis').mt_rand(1000, 9999);
        $array['Procedure_data_in'] = array(
            '_order_id' => $order_id,
            '_credit_cost' => $cash,
            '_credit_code' => $cardNo,
            '_credit_cardholder'=>$username,
            '_credit_idcard'=>$cardHolderId,
            '_credit_deposit_type'=>$type,
            '_externalRefNumber'=>$externalRefNumber

        );
        $array['Procedure_name'] = 'sendprecredit';


        $Procedure = new CallProcedure();
        try{
            $result = $Procedure->CallProcedure_query($array);
            if($result[0][0]["result"]==1 || $result[0][0]["result"]=="1")
            {
                $flag=1;
            }
        }catch (\Exception $ex)
        {
            $returnarray["result"]=5;
            $returnarray["msg"]=$ex->getMessage();
        }

        if($flag==1)
        {
            //接口版本号'13761981309'
            $version = '1.0';
            //交易类型编码
            $txnType = 'PRE';
            //消息状态
            $interactiveStatus = 'TR1';
            //商户编号  由快钱公司分配给商户的 15位唯一标识号。
            $merchantId =Yii::getAlias('@merchantId');
            //终端编号
            $terminalId =Yii::getAlias('@terminalId');
            //tr3回调地址  接收快钱TR3报文的地址
            $tr3Url = Yii::getAlias('@tr3Url');
            //商户端交易时间
            $entryTime = date('YmdHis');
            //信用卡卡号
            $cardNo = $cardNo;
            //卡效期
            $expiredDate = $cardexpiredDate;
            //安全校验值  卡背面后三位
            $cvv2 = $cvv2;
            //交易金额
            $amount = $cash;

            //客户姓名
            $cardHolderName = $username;
            //客户身份证号
            $cardHolderId = $cardHolderId;
            //扩展数据键
            $key = 'phone';
            //扩展数据值
            $value = $phone;

            $cardHolderName  =$this->kq_ck_null($cardHolderName,'cardHolderName');
            $cardHolderId    =$this->kq_ck_null($cardHolderId,'cardHolderId');
            $key             =$this->kq_ck_null($key,'key');
            $value           =$this->kq_ck_null($value,'value');
            $tr3Url          =$this->kq_ck_null($tr3Url,'tr3Url');
            $reqXml = '<?xml version="1.0" encoding="UTF-8"?><MasMessage xmlns="http://www.99bill.com/mas_cnp_merchant_interface"><version>'.$version.'</version><TxnMsgContent><txnType>'.$txnType.'</txnType><interactiveStatus>'.$interactiveStatus.'</interactiveStatus><cardNo>'.$cardNo.'</cardNo><expiredDate>'.$expiredDate.'</expiredDate><cvv2>'.$cvv2.'</cvv2><amount>'.$amount.'</amount><merchantId>'.$merchantId.'</merchantId><terminalId>'.$terminalId.'</terminalId>'.$cardHolderName.$cardHolderId.'<entryTime>'.$entryTime.'</entryTime><externalRefNumber>'.$externalRefNumber.'</externalRefNumber><extMap><extDate>'.$key.$value.'</extDate></extMap>'.$tr3Url.'</TxnMsgContent></MasMessage>';
            $clientcert    = Yii::getAlias('@quickmoneyrsa_clientcert');//"/home/flightsharecar/user_upload/php_demo/cert.pem";
            $clientprikey=Yii::getAlias('@quickmoneyrsa_clientprikey');//"/home/flightsharecar/user_upload/php_demo/private.pem";

            //   echo "<textarea rows=\"20\" cols=\"100\">".$reqXml."</textarea></br>";
            $tuCurl = curl_init();
            $merchantId=Yii::getAlias('@merchantId');//商户编号
            $certPassword=Yii::getAlias('@certPassword');//证书密码
            $loginKey=Yii::getAlias('@loginKey');//商户登录密码
            $loginInfo = array(
                "Authorization: Basic " . base64_encode($merchantId . ":" . $loginKey)
            );
            curl_setopt($tuCurl, CURLOPT_URL, Yii::getAlias('@api_tuCurl'));
            curl_setopt($tuCurl, CURLOPT_HTTPHEADER, $loginInfo);
            curl_setopt($tuCurl,CURLOPT_SSL_VERIFYPEER,false);
            curl_setopt($tuCurl,CURLOPT_SSL_VERIFYHOST,false);
            curl_setopt($tuCurl,CURLOPT_SSLCERTTYPE,'PEM');//证书格式
            curl_setopt($tuCurl,CURLOPT_SSLCERT,$clientcert);//证书路径
            curl_setopt($tuCurl,CURLOPT_SSLCERTPASSWD,$certPassword);//证书密码
            curl_setopt($tuCurl,CURLOPT_SSLKEYTYPE,'PEM');//本地私钥格式
            curl_setopt($tuCurl,CURLOPT_SSLKEY,$clientprikey);//私钥文件路径
            curl_setopt($tuCurl, CURLOPT_POST, 1);//POST
            curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $reqXml);//POST内容中包含报文
            curl_setopt($tuCurl,CURLOPT_TIMEOUT,30);
            curl_setopt($tuCurl,CURLOPT_RETURNTRANSFER, 1);

            $tuData=curl_exec($tuCurl);

//var_dump($tuData);exit;

            if(!$tuData){
                $returnarray["result"]=3;
                $returnarray["msg"]="网络错误".curl_error($tuCurl);




                $this->prefaild($externalRefNumber);
                return $returnarray;

            };



            $obj=simplexml_load_string($tuData,'SimpleXMLElement', LIBXML_NOCDATA);


            if(is_object($obj)){
                $obj=get_object_vars($obj);
            }

            if(array_key_exists("ErrorMsgContent",$obj))
            {
                $array=$this->std_class_object_to_array($obj["ErrorMsgContent"]);
                $returnarray["result"]=2;
                $returnarray["msg"]=$array["errorCode"]."错误信息：".$array["errorMessage"];
                $this->prefaild($externalRefNumber);
            }
            else if(array_key_exists("TxnMsgContent",$obj))
            {
                $array=$this->std_class_object_to_array($obj["TxnMsgContent"]);
                if($array["responseCode"]=="00")
                {
                    $returnarray["result"]=1;
                    $returnarray["msg"]=$array;
                    $this->preinsertintosql($returnarray["result"],$array,1);
                }
                else if($array["responseCode"]=="C0")
                {
                    $returnarray["result"]=0;
                    $returnarray["msg"]="预授权提交成功，真该等待银行端处理";
                    $this->preinsertintosql($returnarray["result"],$array,1);
                }
                else
                {
                    $returnarray["result"]=6;
                    $returnarray["msg"]=$array["responseTextMessage"];//'预授权信息错误';//$array;
                    $this->preinsertintosql($returnarray["result"],$array,1);
                }
            }
            else
            {
                $returnarray["result"]=3;
                $returnarray["msg"]="网络错误";
                $this->prefaild($externalRefNumber);
            }
        }
        else
        {
            //数据库已经存在已提交的预授权
            $returnarray["result"]=4;
            $returnarray["msg"]="数据库已经存在已提交的预授权";

        }
        return $returnarray;

    }


    //确认卡信息
    public   function carinforequre($carcode)
    {
        //交易类型编码
        $txnType = 'INP';
        //信用卡卡号
        $cardNo = $carcode;//'4392268386764048';
        //接口版本号
        $version = '1.0';

        $reqXml = '<?xml version="1.0" encoding="UTF-8"?><MasMessage xmlns="http://www.99bill.com/mas_cnp_merchant_interface"><version>'.$version.'</version><QryCardContent><txnType>'.$txnType.'</txnType><cardNo>'.$cardNo.'</cardNo></QryCardContent></MasMessage>';
        $clientcert    = Yii::getAlias('@quickmoneyrsa_clientcert');//"/home/flightsharecar/user_upload/php_demo/cert.pem";
        $clientprikey=Yii::getAlias('@quickmoneyrsa_clientprikey');//"/home/flightsharecar/user_upload/php_demo/private.pem";
        $tuCurl = curl_init();
        $merchantId=Yii::getAlias('@merchantId');//商户编号
        $certPassword=Yii::getAlias('@certPassword');//证书密码
        $loginKey=Yii::getAlias('@loginKey');//商户登录密码
        $loginInfo = array(
            "Authorization: Basic " . base64_encode($merchantId . ":" . $loginKey)
        );
        curl_setopt($tuCurl, CURLOPT_URL, Yii::getAlias('@sure_cardurl'));

        curl_setopt($tuCurl, CURLOPT_HTTPHEADER, $loginInfo);//请求头中包含merchantId和对应的密码的内容
        //curl_setopt($tuCurl, CURLOPT_USERPWD, $loginKey);//登录用户密码

        curl_setopt($tuCurl,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($tuCurl,CURLOPT_SSL_VERIFYHOST,false);


        curl_setopt($tuCurl,CURLOPT_SSLCERTTYPE,'PEM');//证书格式
        curl_setopt($tuCurl,CURLOPT_SSLCERT,$clientcert);//证书路径
        curl_setopt($tuCurl,CURLOPT_SSLCERTPASSWD,$certPassword);//证书密码

        curl_setopt($tuCurl,CURLOPT_SSLKEYTYPE,'PEM');//本地私钥格式
        curl_setopt($tuCurl,CURLOPT_SSLKEY,$clientprikey);//私钥文件路径

        curl_setopt($tuCurl, CURLOPT_POST, 1);//POST
        curl_setopt($tuCurl, CURLOPT_POSTFIELDS, $reqXml);//POST内容中包含报文


        curl_setopt($tuCurl,CURLOPT_TIMEOUT,30);

        curl_setopt($tuCurl,CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($ch,CURLOPT_URL,$url);

        $tuData=curl_exec($tuCurl);

        $obj=simplexml_load_string($tuData,'SimpleXMLElement', LIBXML_NOCDATA);
        if(is_object($obj)){
            $obj=get_object_vars($obj);
        }

        $flag=2;  //2块钱不支持   1块钱支持 validFlag 快钱VPOS-CNP是否支持 1：快钱支持 2：快钱不支持 1	快钱支持  2	快钱不支持境内卡对应的发卡银行。
        if(array_key_exists("CardInfoContent",$obj))
        {
            $array2=$this->std_class_object_to_array($obj["CardInfoContent"]);
            if(is_array($array2) && array_key_exists("validFlag",$array2))
            {
                $flag=$array2["validFlag"]=='1' || $array2["validFlag"]='2'? 1:2;
            }
        }

        return $flag;
    }

    //航班机场对照数据
    public static function flight_controldata($name){
        $flight=array(
            "北京 首都国际T3"=>"北京首都国际机场",
            "北京 南苑"=>"南苑机场",
            "上海 虹桥国际T2"=>"上海虹桥国际机场",
            "上海 浦东国际T1"=>"上海浦东国际机场",
            "广州 新白云国际--"=>"广州白云国际机场",
            "深圳 宝安国际T3"=>"深圳宝安国际机场",

        );
        $percent='';
        foreach($flight as $key=> $value){
            similar_text($name,$key,$percent) ;
            if($percent>=50){return $value;}
        }
    }

    //调用航班接口
    public  function flight_information($flight_name,$flight_date){


        //配置您申请的appkey
        $appkey = "5a9a21786176031b46be3df12366485e";
        $url = "http://apis.juhe.cn/plan/snew";
        $params = array(
            "name" => $flight_name,//航班号，如:CZ3869
            "key" => $appkey,//APP KEY
            "date" =>$flight_date,//请求时间，如：2012-12-27 （默认当天时间） 为空的话默认为今天
            "dtype" => "",//返回类型，如：json 或者 xml（默认json）
        );
        $paramstring = http_build_query($params);
        $content =$this-> juhecurl($url,$paramstring);
        $result=json_decode($content,true);
        return $result;
    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */

    function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();

        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'JuheData' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }


    public function preinsertintosql($re,$array,$type)
    {
        if(array_key_exists("txnType",$array))
            $postdate['_txnType']=$array["txnType"];
        else
            $postdate['_txnType']="";

        if(array_key_exists("interactiveStatus",$array))
            $postdate['_interactiveStatus']=$array["interactiveStatus"];
        else
            $postdate['_interactiveStatus']="";

        if(array_key_exists("amount",$array))
            $postdate['_amount']=$array["amount"];
        else
            $postdate['_amount']="";

        if(array_key_exists("merchantId",$array))
            $postdate['_merchantId']=$array["merchantId"];
        else
            $postdate['_merchantId']="";

        if(array_key_exists("terminalId",$array))
            $postdate['_terminalId']=$array["terminalId"];
        else
            $postdate['_terminalId']="";

        if(array_key_exists("entryTime",$array))
        {
            $postdate['_entryTime']=$array["entryTime"];
            $postdate['_entryTime2']=date("Y-m-d h:i:s",strtotime($array["entryTime"]));
        }
        else
        {
            $postdate['_entryTime']="";
            $postdate['_entryTime2']="";
        }
        if(array_key_exists("externalRefNumber",$array))
            $postdate['_externalRefNumber']=$array["externalRefNumber"];
        else
            $postdate['_externalRefNumber']="";
        if(array_key_exists("transTime",$array))
            $postdate['_transTime']=$array["transTime"];
        else
            $postdate['_transTime']="";

        if(array_key_exists("refNumber",$array))
            $postdate['_refNumber']=$array["refNumber"];
        else
            $postdate['_refNumber']="";

        if(array_key_exists("responseCode",$array))
            $postdate['_responseCode']=$array["responseCode"];
        else
            $postdate['_responseCode']="";

        if(array_key_exists("responseTextMessage",$array))
            $postdate['_responseTextMessage']=$array["responseTextMessage"];
        else
            $postdate['_responseTextMessage']="";

        if(array_key_exists("cardOrg",$array))
            $postdate['_cardOrg']=$array["cardOrg"];
        else
            $postdate['_cardOrg']="";

        if(array_key_exists("issuer",$array))
            $postdate['_issuer']=$array["issuer"];
        else
            $postdate['_issuer']="";

        if(array_key_exists("storableCardNo",$array))
            $postdate['_storableCardNo']=$array["storableCardNo"];
        else
            $postdate['_storableCardNo']="";

        if(array_key_exists("authorizationCode",$array))
            $postdate['_authorizationCode']=$array["authorizationCode"];
        else
            $postdate['_authorizationCode']="";


        $postdate['_r']=$re;
        $postdate['_version']="1.0";
        if(array_key_exists("origRefNumber",$array))
            $postdate['_origRefNumber']=$array["origRefNumber"];
        else
            $postdate['_origRefNumber']="";
        $postdate['_pre_type']=$type;


        if($type==1)
        {


            $ProcedureData=array(
                'Procedure_name'=>'authorization_reback',
                'Procedure_data_in'=>$postdate
            );
        }
        else if($type==2)
        {
            $ProcedureData=array(
                'Procedure_name'=>'authorization_rebackforjiaoyi',
                'Procedure_data_in'=>$postdate
            );
        }
        else{

        }

        $Procedure = new CallProcedure();
        try {
            $result = $Procedure->CallProcedure_query($ProcedureData);


            return $result[0][0]["result"];
        }catch (\Exception $ex)
        {
            return $ex->getMessage();
        }
    }

    //明确标记预授权失败
    public function prefaild($externalRefNumber)
    {
        $postdate['_externalRefNumber']=$externalRefNumber;
        $ProcedureData=array(
            'Procedure_name'=>'authorization_prefaild',
            'Procedure_data_in'=>$postdate
        );
        $Procedure = new CallProcedure();
        try {
            $result = $Procedure->CallProcedure_execute($ProcedureData);

        }catch (\Exception $ex)
        {
            return $ex->getMessage();
        }
    }
    public static function std_class_object_to_array($stdclassobject)
    {
        $_array = is_object($stdclassobject) ? get_object_vars($stdclassobject) : $stdclassobject;
        foreach ($_array as $key => $value) {
            $value = (is_array($value) || is_object($value)) ? std_class_object_to_array($value) : $value;
            $array[$key] = $value;
        }
        return $array;
    }

    public static function kq_ck_null($kq_va,$kq_na)
    {
        if($kq_va == ""){$kq_va="";
        }else
        {return '<'.$kq_na.'>'.$kq_va.'</'.$kq_na.'>';
        }
    }




}


